<template>
  <div class="main">
    <div class="top">
      <div class="time">
        <span>{{ currentTime }}</span>
        <span>星期{{ currentDay }}</span>
      </div>
      <div style="margin-left: 25%">
        <span style="width: 70px; height: 70px"
          ><img src="../assets/logo/logo.jpg" style="width: 70px; height: 70px"
        /></span>
        <span class="headline"> 情绪识别系统</span>
      </div>
    </div>
    <div class="box">
      <div class="bigBox">
        <div class="boxTest">
          <img
            src="../assets/svg/sxt.svg"
            style="width: 50px; height: 50px; margin-right: 10px"
          />
          <span class="userText" style="text-align: center; font-size: 20px"
            >摄像头数量：{{ cameraCount }}</span
          >
        </div>
        <div class="boxTest">
          <img
            src="../assets/svg/yh.svg"
            style="width: 50px; height: 50px; margin-right: 10px"
          />
          <span class="userText" style="text-align: center; font-size: 20px"
            >管理人员数量：{{ headcount }}</span
          >
        </div>
        <div class="boxTest">
          <img
            src="../assets/svg/jrbjsl.svg"
            style="width: 50px; height: 50px; margin-right: 10px"
          />
          <span class="userText" style="text-align: center; font-size: 20px"
            >今日报警数量：{{ warnCount }}</span
          >
        </div>
        <div class="boxTest">
          <img
            src="../assets/svg/ycl.svg"
            style="width: 50px; height: 50px; margin-right: 10px"
          />
          <span class="userText" style="text-align: center; font-size: 20px"
            >今日已处理数量：{{ processed }}</span
          >
        </div>
      </div>
      <div class="bigBox">
        <div
          style="
            width: 100%;
            height: 50px;
            text-align: center;
            font-size: 20px;
            line-height: 50px;
            color: #fff;
          "
        >
          <span>最近30天锂电池和电瓶车的报警数量</span>
        </div>
        <div
          id="monthChart"
          style="width: 100%; height: calc(100% - 50px)"
        ></div>
      </div>
      <div class="bigBox">
        <div
          style="
            width: 100%;
            height: 50px;
            text-align: center;
            font-size: 20px;
            line-height: 50px;
            color: #fff;
          "
        >
          <span>电瓶车与锂电池报警数据 / 百分比</span>
        </div>
        <div id="allChart" style="width: 100%; height: calc(100% - 50px)"></div>
      </div>
      <div class="bigBox">
        <div
          style="
            width: 100%;
            height: 50px;
            text-align: center;
            font-size: 20px;
            line-height: 50px;
            color: #fff;
          "
        >
          最近10条报警信息
        </div>
        <div style="width: 100%; height: calc(100% - 50px)">
          <el-table
            v-loading="loading"
            :data="warnList"
            style="background-color: #1a1835"
            :show-header="false"
            height="100%"
            class="hidden-scrollbar"
          >
            <el-table-column
              align="center"
              label="报警类别"
              prop="warnType"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              label="报警地址"
              align="center"
              prop="alarmAddress"
            />
            <el-table-column
              label="报警摄像头"
              align="center"
              prop="alarmCamera"
            />
            <el-table-column
              label="识别相似度"
              align="center"
              prop="warnSimilarity"
            />
            <el-table-column
              label="报警信息是否处理"
              align="center"
              prop="warnHandle"
            >
              <template v-slot="{ row }">
                <el-tag :type="row.warnHandle == 0 ? 'danger ' : 'success'">{{
                  row.warnHandle == 0 ? "未处理" : "已处理"
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="时间"
              align="center"
              prop="createTime"
              width="160"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import "echarts-gl";
import {
  getWarnCount,
  getBatteryWarnCount,
  getAllWarnCount,
} from "@/api/index.js";
import { listWarnNo } from "@/api/camera/warn.js";
export default {
  name: "index",
  data() {
    return {
      currentTime: "",
      currentDay: "",
      loading: false,
      timeInterval: null,
      lineChart: null,
      pieChart: null,
      warnCount: null,
      cameraCount: null,
      electromobile: null,
      processed: null,
      headcount: null,
      lithium: null,
      time: null,
      ddcName: null,
      ldcName: null,
      warnList: [],
      //地址
      alarmAddress: "",
      //报警摄像头
      alarmCamera: "",
      windowWidth: window.innerWidth,
    };
  },

  methods: {
    updateWindowWidth() {
      this.windowWidth = window.innerWidth;
    },
    //查询该部门下的今日报警数量
    getWarnCount() {
      getWarnCount().then((res) => {
        this.headcount = res.data.usersNumber;
        this.warnCount = res.data.alarmsTodayNumber;
        this.cameraCount = res.data.cameraNumber;
        this.processed = res.data.handleAlarmsTodayNumber;
      });
    },
    //最近30天锂电池和电瓶车的报警数量
    getBatteryWarnCount() {
      getBatteryWarnCount().then((res) => {
        this.electromobile = res.data[0].data;
        this.time = res.data[0].date;
        this.lithium = res.data[1].data;
      });
    },
    //查询所有报警数量
    getAllWarnCount() {
      getAllWarnCount().then((res) => {
        this.ddcName = res.data.电瓶车;
        this.ldcName = res.data.锂电池;
        console.log(this.ddcName, this.ldcName, 5555555555);
      });
    },
    // 获取报警列表
    // getWarnList () {
    //   listWarnNo().then(res => {
    //     this.warnList = res.data;
    //     this.warnList.forEach((v) => {
    //       v.alarmAddress = v.warnAddress.split(" ")[0];
    //       v.alarmCamera = v.warnAddress.split(" ")[1];
    //     });
    //     console.log(this.warnList, 6666666666);
    //   });
    // },
    getWarnList() {
      listWarnNo().then((res) => {
        const allWarnList = res.data;
        const top10WarnList = allWarnList.slice(0, 10);
        this.warnList = top10WarnList.map((v) => {
          return {
            ...v,
            alarmAddress: v.warnAddress.split(" ")[0],
            alarmCamera: v.warnAddress.split(" ")[1],
          };
        });

        console.log(this.warnList, 6666666666);
      });
    },
    // 更新实时时间
    updateTime() {
      const now = new Date();
      this.currentTime = `${now.getFullYear()}-${String(
        now.getMonth() + 1
      ).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(
        now.getHours()
      ).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}:${String(
        now.getSeconds()
      ).padStart(2, "0")}`;
    },
    // 获取实时星期
    updateDay() {
      const now = new Date();
      this.currentDay = ["日", "一", "二", "三", "四", "五", "六"][
        now.getDay()
      ];
    },
    startTimer() {
      this.updateTime(); // 初始化时间
      this.updateDay(); // 初始化星期
      this.timeInterval = setInterval(() => {
        this.updateTime();
      }, 1000); // 每秒更新一次
    },
    initMonthChart() {
      const lineChart = echarts.init(document.getElementById("monthChart"));
      let xData = this.time;

      let option = {
        backgroundColor: "#1A1835",

        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            textStyle: {
              color: "#fff",
            },
          },
        },
        grid: {
          borderWidth: 0,
          top: 110,
          bottom: 95,
          textStyle: {
            color: "#fff",
          },
        },
        legend: {
          x: "46%",
          top: "11%",
          textStyle: {
            color: "#90979c",
          },
          data: ["电瓶车预警", "锂电池预警"],
        },

        calculable: true,
        xAxis: [
          {
            type: "category",
            axisLine: {
              lineStyle: {
                color: "rgba(204,187,225,0.5)",
              },
            },
            splitLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            data: xData,
          },
        ],

        yAxis: [
          {
            type: "value",
            splitLine: {
              show: false,
            },
            axisLine: {
              lineStyle: {
                color: "rgba(204,187,225,0.5)",
              },
            },
          },
        ],
        series: [
          {
            name: "电瓶车预警",
            type: "line",
            symbolSize: 10,
            symbol: "circle",
            itemStyle: {
              color: "#6f7de3",
            },
            markPoint: {
              label: {
                normal: {
                  textStyle: {
                    color: "#fff",
                  },
                },
              },
            },
            data: this.electromobile,
          },
          {
            name: "锂电池预警",
            type: "line",
            symbolSize: 10,
            symbol: "circle",
            itemStyle: {
              color: "#c257F6",
            },
            markPoint: {
              label: {
                normal: {
                  textStyle: {
                    color: "#fff",
                  },
                },
              },
            },
            data: this.lithium,
          },
        ],
      };
      lineChart.setOption(option);
      window.addEventListener("resize", function () {
        lineChart.resize();
      });
    },
    initAllChart() {
      //简单的echart图表
      const pieChart = echarts.init(document.getElementById("allChart"));
      // let pieOption = {
      //   tooltip: {
      //     trigger: 'item',
      //     formatter: "{a} <br/>{b} : {c} ({d}%)"
      //   },
      //   legend: {
      //     orient: 'vertical',
      //     left: 'left',
      //     data: ['电瓶车', '锂电池'],
      //     textStyle: {
      //       color: '#fff' // 设置字体颜色为白色
      //     },

      //   },
      //   series: [
      //     {
      //       name: '报警占比',
      //       type: 'pie',
      //       radius: '55%',
      //       center: ['50%', '60%'],
      //       data: [
      //         { value: this.ddcName, name: '电瓶车' },
      //         { value: this.ldcName, name: '锂电池' },],
      //       textStyle: { // 设置标签字体样式
      //         color: '#fff' // 设置字体颜色为白色
      //       },
      //       itemStyle: {
      //         emphasis: {
      //           shadowBlur: 10,
      //           shadowOffsetX: 0,
      //           shadowColor: 'rgba(0, 0, 0, 0.5)'
      //         }
      //       }
      //     }
      //   ]
      // };
      // 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
      function getParametricEquation(
        startRatio,
        endRatio,
        isSelected,
        isHovered,
        k,
        h
      ) {
        // 计算
        const midRatio = (startRatio + endRatio) / 2;
        const startRadian = startRatio * Math.PI * 2;
        const endRadian = endRatio * Math.PI * 2;
        const midRadian = midRatio * Math.PI * 2;
        // 如果只有一个扇形，则不实现选中效果。
        if (startRatio === 0 && endRatio === 1) {
          isSelected = false;
        }
        // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
        k = 1;
        // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
        const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
        const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;
        // 计算高亮效果的放大比例（未高亮，则比例为 1）
        const hoverRate = isHovered ? 1.05 : 1;
        // 返回曲面参数方程
        return {
          u: {
            min: -Math.PI,
            max: Math.PI * 3,
            step: Math.PI / 32,
          },
          v: {
            min: 0,
            max: Math.PI * 2,
            step: Math.PI / 20,
          },
          x: function (u, v) {
            if (u < startRadian) {
              return (
                offsetX +
                Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
              );
            }
            if (u > endRadian) {
              return (
                offsetX +
                Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
              );
            }
            return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
          },
          y: function (u, v) {
            if (u < startRadian) {
              return (
                offsetY +
                Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
              );
            }
            if (u > endRadian) {
              return (
                offsetY +
                Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
              );
            }
            return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
          },
          z: function (u, v) {
            if (u < -Math.PI * 0.5) {
              return Math.sin(u);
            }
            if (u > Math.PI * 2.5) {
              return Math.sin(u) * h * 0.1;
            }
            return Math.sin(v) > 0 ? 1 * h * 0.1 : -1;
          },
        };
      }

      /**
       * 绘制3d图
       * @param pieData 总数据
       * @param internalDiameterRatio:透明的空心占比
       * @param distance 视角到主体的距离
       * @param alpha 旋转角度
       * @param pieHeight 立体的高度
       * @param opacity 饼或者环的透明度
       */
      function getPie3D(
        pieData,
        internalDiameterRatio,
        distance,
        alpha,
        pieHeight,
        opacity = 1
      ) {
        const series = [];
        let sumValue = 0;
        let startValue = 0;
        let endValue = 0;
        const legendData = [];
        const k =
          typeof internalDiameterRatio !== "undefined"
            ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio)
            : 1 / 3;
        // 为每一个饼图数据，生成一个 series-surface 配置
        for (let i = 0; i < pieData.length; i += 1) {
          sumValue += pieData[i].value;
          const seriesItem = {
            name:
              typeof pieData[i].name === "undefined"
                ? `series${i}`
                : pieData[i].name,
            type: "surface",
            parametric: true,
            wireframe: {
              show: false,
            },
            pieData: pieData[i],
            pieStatus: {
              selected: false,
              hovered: false,
              k: k,
            },
          };
          if (typeof pieData[i].itemStyle !== "undefined") {
            const itemStyle = {};
            if (typeof pieData[i].itemStyle.color !== "undefined") {
              itemStyle.color = pieData[i].itemStyle.color;
            }
            if (typeof pieData[i].itemStyle.opacity !== "undefined") {
              itemStyle.opacity = pieData[i].itemStyle.opacity;
            }
            seriesItem.itemStyle = itemStyle;
          }
          series.push(seriesItem);
        }
        // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
        // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
        for (let i = 0; i < series.length; i += 1) {
          endValue = startValue + series[i].pieData.value;
          series[i].pieData.startRatio = startValue / sumValue;
          series[i].pieData.endRatio = endValue / sumValue;
          console.log(
            series[i].pieData.startRatio,
            series[i].pieData.endRatio,
            false,
            false,
            k,
            series[i].pieData.value
          );
          series[i].parametricEquation = getParametricEquation(
            series[i].pieData.startRatio,
            series[i].pieData.endRatio,
            false,
            false,
            k,
            series[i].pieData.value
          );
          startValue = endValue;
          legendData.push(series[i].name);
        }
        return series;
      }

      const optionsData = [
        {
          name: "电瓶车",
          value: this.ddcName,
          itemStyle: {
            color: "#c257f6",
            // opacity: 1,
          },
        },
        {
          name: "锂电池",
          value: this.ldcName,
          itemStyle: {
            color: "#6f7de3",
            // opacity: 1,
          },
        },
      ];

      const series = getPie3D(optionsData, 0.8, 240, 28, 26, 0.5);

      series.push({
        name: "pie2d",
        type: "pie",
        label: {
          opacity: 1,
          fontSize: 13,
          lineHeight: 20,
        },
        labelLine: {
          length: 30,
          length2: 30,
        },
        startAngle: -30, //起始角度，支持范围[0, 360]。
        clockwise: false, //饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式
        radius: ["20%", "50%"],
        center: ["50%", "50%"],
        data: optionsData,
        itemStyle: {
          opacity: 0,
        },
      });

      let pieOption = {
        legend: {
          tooltip: {
            show: true,
          },
          data: ["电瓶车", "锂电池"],
          bottom: "10%",
          textStyle: {
            color: "#fff",
            fontSize: 12,
          },
        },
        tooltip: {
          formatter: (params) => {
            if (
              params.seriesName !== "mouseoutSeries" &&
              params.seriesName !== "pie2d"
            ) {
              let bfb = (
                (option.series[params.seriesIndex].pieData.endRatio -
                  option.series[params.seriesIndex].pieData.startRatio) *
                100
              ).toFixed(2);
              return (
                `${params.seriesName}<br/>` +
                `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>` +
                `${bfb}%`
              );
            }
          },
        },
        // title: {
        //   text: '3D 饼图',
        //   x: 'center',
        //   top: '20',
        //   textStyle: {
        //     color: '#fff',
        //     fontSize: 22,
        //   },
        // },
        backgroundColor: "#1a1835",
        labelLine: {
          show: true,
          lineStyle: {
            color: "#7BC0CB",
          },
        },
        label: {
          show: true,
          position: "outside",
          formatter: "{b} \n{c}  /  {d}%", // {b}：系列名称。{c}：数据值。{d}：百分比。
        },
        xAxis3D: {
          min: -1,
          max: 1,
        },
        yAxis3D: {
          min: -1,
          max: 1,
        },
        zAxis3D: {
          min: -1,
          max: 1,
        },
        grid3D: {
          show: false,
          boxHeight: 1.5, // 三维笛卡尔坐标系在三维场景中的高度
          viewControl: {
            alpha: 40,
            beta: 40,
            distance: 500, //调整视角到主体的距离，类似调整zoom
            rotateSensitivity: 0, // 设置为0无法旋转
            zoomSensitivity: 0, // 设置为0无法缩放
            panSensitivity: 0, // 设置为0无法平移
            autoRotate: true, // 自动旋转
          },
        },
        series: series,
      };

      pieChart.setOption(pieOption);
      window.addEventListener("resize", function () {
        pieChart.resize();
      });
    },
  },
  mounted() {
    if (this.$store.state.app.sidebar.opened == true) {
      this.$store.dispatch("app/toggleSideBar");
    }
    this.startTimer();
    window.setTimeout(() => {
      this.initMonthChart();
      this.initAllChart(); // 在组件挂载后初始化图表
    }, 700);
    this.$store.dispatch("tagsView/delView", this.$route);
    window.addEventListener("resize", this.updateWindowWidth);
  },
  created() {
    this.getWarnCount();
    this.getBatteryWarnCount();
    this.getAllWarnCount();
    this.getWarnList();
  },
  beforeUnmount() {
    if (this.timeInterval) {
      clearInterval(this.timeInterval); // 清理定时器
    }
    if (this.lineChart) {
      this.lineChart.dispose(); // 清理 ECharts 实例
    }
    if (this.pieChart) {
      this.pieChart.dispose(); // 清理 ECharts 实例
    }
  },
};
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100vh;
  background-color: rgb(8, 8, 8);
  //background: #25262f;

  .top {
    background-color: #1a1835;
    width: 100%;
    height: 70px;
    display: flex;
    .time {
      display: flex;
      flex-direction: column;
      width: 10%;
      text-align: center;
      height: 100%;
      line-height: 25px;
      font-size: 13px;
      color: #fff;
      flex-direction: column;
      justify-content: center;
    }
    .headline {
      color: #fff;
      position: relative;
      bottom: 20px;
      font-size: 40px;
    }
  }

  .box {
    width: 100%;
    height: calc(100vh - 60px);
    display: flex;
    flex-wrap: wrap;
    .bigBox {
      width: 48%;
      height: 48%;
      display: flex;
      -ms-flex-wrap: wrap;
      flex-wrap: wrap;
      justify-content: space-evenly;
      margin-bottom: 20px;
      align-items: center;
      // border-radius: 20px;
      border-top-left-radius: 20px;
      border-top-right-radius: 20px;
      margin: 1%;
      margin-left: 1%;
      background-color: #1a1835;

      .boxTest {
        //透明度
        opacity: 0.8;
        border: 0.5px solid #fff;
        width: 40%;
        height: 100px;
        margin-left: 20px;
        margin-top: 20px;
        color: #fff;
        //background-color: aqua;
        text-align: center;
        //  line-height: 100px;
        font-size: 20px;
        border-radius: 20px;

        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
::v-deep .el-table tr {
  background-color: #1a1835 !important;
}
::v-deep .hidden-scrollbar {
  /* Hide scrollbars on Webkit-based browsers (e.g., Chrome, Safari) */
  ::-webkit-scrollbar {
    width: 0; /* No scrollbar width */
    background: transparent; /* Transparent background to remove scrollbar */
  }
}
::v-deep .el-table {
  position: relative;
  overflow: hidden;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  width: 100%;
  max-width: 100%;
  font-size: 14px;
  color: #ffffff;
}
::v-deep .el-table th.el-table__cell.is-leaf,
.el-table td.el-table__cell {
  border-bottom: none !important;
}
::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #212e3e !important;
}
</style>
